new Vue({
    el: '#app',
    data: {
        userInfo: {
            userName: '',
            roleId: ''
        },
        users: [],
        totalUsers: 0, // 总用户数
        adminUsers: 0, // 管理员用户数
        parkingAdminUsers: 0, // 停车场管理员用户数
        regularUsers: 0, // 普通用户数
        searchKey: '',
        showModal: false,
        isEdit: false,
        form: {
            userId: '',
            userName: '',
            realName: '',
            password: '',
            roleId: '2',
            userPhone: '',
        
        },
    },
    created() {
        this.loadUserInfo();
        this.loadUsers();
    },
    methods: {
        loadUserInfo() {
            axios.get('../../userInfo')
                .then(response => {
                    if (response.data.success) {
                        this.userInfo = response.data.data;
                    }
                })
                .catch(error => {
                    console.error('Error loading user info:', error);
                });
        },
        loadUsers() {
            axios.get('../../user/list')
                .then(response => {
                    if (response.data.success) {
                        this.users = response.data.data;
                        this.totalUsers = this.users.length;
                        this.adminUsers = this.users.filter(user => user.roleId === '1').length;
                        this.parkingAdminUsers = this.users.filter(user => user.roleId === '2').length;
                        this.regularUsers = this.users.filter(user => user.roleId === '3').length;
                    }
                })
                .catch(error => {
                    console.error('Error loading users:', error);
                });
        },
        getRoleName(roleId) {
            switch (roleId) {
                case '1': return '系统管理员';
                case '2': return '停车场管理员';
                case '3': return '普通用户';
                default: return '未知';
            }
        },

        handleSearch() {
            if (this.searchKey) {
                const results = this.users.filter(user => 
                    (user.userName && user.userName.includes(this.searchKey)) || 
                    (user.realName && user.realName.includes(this.searchKey))
                );
    
                if( results.length === 0) {
                    alert("未找到该用户");
                    return;
                }
                this.users = results; // 更新用户列表为搜索结果
            } else {
                this.loadUsers(); // 如果没有搜索关键字，重新获取所有用户
            }
        },

        showAddForm() {
            this.isEdit = false;
            this.form = {
                userId: '',
                userName: '',
                realName: '',
                password: '',
                roleId: '2',
                userPhone: ''
            };
            this.showModal = true;
        },
        showEditForm(user) {
            this.isEdit = true;
            this.form = { ...user };
            delete this.form.password;  // 编辑时不需要密码字段
            this.showModal = true;
        },
        closeModal() {
            this.showModal = false;
            this.form = {
                userId: '',
                userName: '',
                realName: '',
                password: '',
                roleId: '2',
                userPhone: ''
            };
        },
        submitForm() {
            const url = this.isEdit ? '../../user/update' : '../../user/add';
            const params = new URLSearchParams();
            Object.keys(this.form).forEach(key => {
                if (this.form[key] !== undefined && this.form[key] !== null) {
                    params.append(key, this.form[key]);
                }
            });

            axios.post(url, params)
                .then(response => {
                    if (response.data.success) {
                        this.loadUsers();
                        this.closeModal();
                    } else {
                        alert(response.data.message || '操作失败');
                    }
                })
                .catch(error => {
                    console.error('Error submitting form:', error);
                    alert('系统错误，请稍后重试');
                });
        },
        deleteUser(userId) {
            if (confirm('确定要删除这个用户吗？')) {
                const params = new URLSearchParams();
                params.append('userId', userId);

                axios.post('../../user/delete', params)
                    .then(response => {
                        if (response.data.success) {
                            this.loadUsers();
                        } else {
                            alert(response.data.message || '删除失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error deleting user:', error);
                        alert('系统错误，请稍后重试');
                    });
            }
        },
        handleLogout() {
            axios.post('../../logout')
                .then(() => {
                    window.location.href = '../../login.html';
                })
                .catch(error => {
                    console.error('Error during logout:', error);
                });
        }
    }
}); 